<template>
  <base-modal
    :show.sync="show"
    width="500px"
    class="editpermiss-dialog"
    @closed="onClose"
  >
    <div slot="title">
      <span class="el-dialog__title">{{$t('common.base.editPermission')}}</span>
    </div>
    <div class="base-modal-content">
      <div v-for="(item, i) in modalList" :key="i">
        <label>{{ item.name }}</label>
        <div @click="handleClick(i)">
            {{ item.selectAll.length ? joinNameList(item.selectAll) : $t('task.setting.taskAdditionalSetting.clickToSelect') }}
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="onSubmit()">{{$t('common.base.makeSure')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
/* enum */
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser/model/enum';
/* api */
import * as settingTaskApi from '@src/api/SettingTaskApi';
import { t } from '@src/locales'

export default {
  name: 'card-select-user-dialog',
  props: {
    taskCard: {
      type: Object,
      default: () => ({}),
    },
    taskTypeId: {
      type: String,
    },
    visiable: {
      type: Boolean,
    },
  },
  data() {
    return {
        show: false,
        modalList: [
          { objectType: 0, name: t('common.base.viewPermission'), selectAll: []},
          { objectType: 1, name: t('common.base.addPermission'), selectAll: []},
          { objectType: 2, name: t('common.base.editPermission'), selectAll: []},
          { objectType: 3, name: t('common.base.deletePermission'), selectAll: []},
        ],
        loading: true
    };
  },
  watch: {
    visiable(newValue) {
      this.show = newValue;

      if(newValue){
        this.getTaskRangeList();
      }
    }
  },
  methods: {
    // 获取所有权限
    async getTaskRangeList(){
      try {
        let url = 'getTaskRangeList';
        if(this.taskCard.isSetObject === 'add') url = 'getDefaultTaskRange';

        this.loading = true;
        const params = {
          taskTypeId: this.taskTypeId,
          objectId: this.taskCard.id
        }
        const { code, message, result } = await settingTaskApi[url](params);
        this.loading = false;
        if(code !== 0) return this.$message.error(message);

        result.forEach(x => {
          let allList = [];
          
          for(let k in x.taskRangeTypeVO){
            if(x.taskRangeTypeVO[k]){
              allList = allList.concat(x.taskRangeTypeVO[k]);
            };
          }

          this.setDataFrom(x.taskRangeTypeVO, x.objectType);
          this.modalList[x.objectType].selectAll = allList;
        })
      }catch(e) {
        console.log('getTaskRangeList', e)
      }
    },
    // 拼接名称
    joinNameList(vList){
      return vList.map(x => x.name || x.displayName).join('，');
    },
    // 权限范围
    handleClick(i) {
      let options = {
        title: t('task.setting.taskAdditionalSetting.permissionTitle'),
        selectedAll: this.modalList[i].selectAll || [],
        max: -1,
        isTag: true,
        showSpAll: true, // 是否显示虚拟的总服务商
        mode: BaseSelectUserModeEnum.Filter
      };
      
      return this.$fast.select.multi.all(options).then(result => {
        if(result.status == 0) {
          this.setDataFrom(result?.data, i);
          this.modalList[i].selectAll = result?.data?.all || [];
        }
      })
        .catch(err => console.error(err))
    },
    setDataFrom(data = {}, index){
      const { 
        // 选人组件返回字段
        all,
        deptIds, 
        roleIds, 
        serviceProviderIds, 
        userIds, 

        // 接口返回字段
        tags,
        roles,
        providers,
        users
      } = data;

      const taskRangeTypeForm = {};
      taskRangeTypeForm.tagIds = deptIds || (tags && tags.map(x => x.id));
      taskRangeTypeForm.roleIds = roleIds || (roles && roles.map(x => x.id));
      taskRangeTypeForm.tenantProviderIds = serviceProviderIds || (providers && providers.map(x => x.id));
      // fix: 21815, userIds数据优先取all里面的
      taskRangeTypeForm.userIds = (all && all.filter(x => x.userId).map(x => x.userId)) || userIds || (users && users.map(x => x.userId));

      this.$set(this.modalList[index], 'taskRangeTypeForm', taskRangeTypeForm);
    },  
    // 关闭弹窗
    onClose(){
        this.$emit('onClose');
    },
    // 提交
    async onSubmit(){
      try{ 
        const paramsList = this.modalList.map(x => {
          return {
            taskTypeId: this.taskTypeId,
            objectId: this.taskCard.id,
            objectType: x.objectType,
            taskRangeTypeForm: x.taskRangeTypeForm || {}
          }
        })
        const { code, message } = await settingTaskApi.saveOrUpdateTaskRange(paramsList);
        if(code !== 0) return this.$message.error(message);

        this.$message.success(t('task.setting.settingSuccess'));
        // add添加 set设置过使用权限的
        if(this.taskCard.isSetObject){
          this.$emit('update', 'set');
        }
        this.onClose();
      }catch(e){
        console.log('onSubmit: ', e)
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.editpermiss-dialog {
    cursor: auto;
  .base-modal-header {
    display: flex;
    justify-content: space-between;
    .el-dialog__title {
      font-size: 16px;
      font-weight: 700;
    }
    .el-tooltip {
      color: #999;
    }
  }
  .base-modal-content {
    >div {
        margin-bottom: 16px;

        >label {
            margin-bottom: 8px;
            color: $text-color-primary;
        }
        >div {
            font-size: 14px;
            cursor: pointer;
            width: 100%;
            padding: 5px;
            text-align: center;
            color: $text-color-regular;
            border: 1px solid #cbd6e2;
            border-radius: $button-radius-base;
            background-color: #f5f8fa;

            @include text-ellipsis;
        }
    }
  }
}
</style>
